<?php
error_reporting(0);

if(!file_exists("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imdbnrs/")){
	umask(0);
	mkdir("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imdbnrs/");
}

$imdbnr		= 0;

if(isset($argv[1])){ // Movie path is given
	$movfile = substr($argv[1], strrpos($argv[1], "/")+1);
	$movdir  = substr($argv[1], 0, strrpos($argv[1], "/"));
	$ext = strtolower(substr($movfile, strrpos($movfile, ".")+1));
		
	
	
	
	$title = substr($movfile, 0, strlen($movfile) - strlen($ext) - 1);
	// Now clean "parts" options - based on ATVFiles default config (wiki.akwardtv.org)
	$title = preg_replace("/[_\.-]+cd[_\.-]*([0-9a-d]+)/","",$title);
	$title = preg_replace("/[_\.-]+dvd[_\.-]*([0-9a-d]+)/","",$title);
	$title = preg_replace("/[_\.-]+part[_\.-]*([0-9a-d]+)/","",$title);
	$title = preg_replace("/[_\.-]*sample[_\.-]*([0-9a-d]+)/","",$title);
	$title = preg_replace("/[_\.-]*trailer[_\.-]*([0-9a-d]+)/","",$title);

	$matches = array();
	if(preg_match("/^t*(\d{6,})\D*/",$imdbfilename,$matches)){
		$imdbnr = $matches[1];
	}
	
	// Check whether it is in the saved area (cache)
	if(file_exists("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imdbnrs/".$title.".txt")){
		$imdbnr = file("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imdbnrs/".$title.".txt");
		$imdbnr = $imdbnr[0];
	}
	
	// If not, check whether we already have an xml file
	if($imdbnr <= 0){
		if(file_exists(str_replace($ext,"xml",$argv[1]))){
			$temp = file(str_replace($ext,"xml",$argv[1]));
			foreach($temp as $line){
				$matches = array();
				if(preg_match("/\<imdbnr\>(\d+)\<\/imdbnr\>/",$line,$matches)){
					$imdbnr = $matches[1];
				}
			}
		}
	}

	// Or maybe we are working in a separate directory?
	if($imdbnr <= 0){
		if(file_exists($movdir."/imdbnr.txt")){
			$temp = file($movdir."/imdbnr.txt");
			$imdbnr = $temp[0];
		}
	}

	// If not, try to find out imdbnr
	if($imdbnr <= 0){
		require ("imdbsearch.class.php");
		$search = new imdbsearch();
		$search->setsearchname($title);
		$results = $search->results();
		foreach ($results as $res) {
			if(str_replace(" ","",strtolower($res->title())) == str_replace(".","",str_replace(" ","",strtolower($title)))){
				$imdbnr = $res->imdbid();
				break;
			}
		}
	}
	
	// Or return 0


	if($imdbnr > 0){
		$out = fopen("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imdbnrs/".$title.".txt","w");
		fwrite($out,$imdbnr);
	}
}


echo $imdbnr;
exit;

?>